<?php

namespace App\Console\Commands\Plane\PlaneOrder;

use App\Events\Plane\PlaneOrder\PlaneOrderTicketedEvent;
use App\Models\Plane\PlaneOrders\PlaneOrder;
use App\Models\Plane\PlaneOrders\Repositories\Interfaces\PlaneOrderRepositoryInterface;
use Carbon\Carbon;
use Exception;
use Illuminate\Console\Command;
use Log;

class TicketingOrderTryToTicketedOrFailed extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'plane.ticketing.order:try_to_ticket';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '出票中的订单主动尝试更新出票状态';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $planeOrderRepo   = app(PlaneOrderRepositoryInterface::class);
        $ticketing_orders = $planeOrderRepo->getTicketingOrders();
        // 这里只拉去 向服务商支付后 10分钟的 订单
        /**
         * @var PlaneOrder $order_info
         */
        foreach ($ticketing_orders as $order_info) {
            // 这里过滤 支付时间 10分钟内的订单那
            if (!$order_info->provider_pay_at) {
                continue;
            }

            if (Carbon::now()->diffInMinutes($order_info->provider_pay_at) < 10) {
                continue;
            }

            try {
                $this->try2ticket($order_info);
                $this->ticket_failed($order_info);
            } catch (Exception $exception) {
                Log::error("计划任务拉取出票中的订单状态:{$order_info->getOrderSn()},失败,{$exception->getMessage()},{$exception->getFile()},{$exception->getLine()}");
            }
        }
    }

    private function try2ticket(PlaneOrder $order_info)
    {
        /**
         * 如果取出票中的订单不需要传入子单号
         */
        $provider_order_detail = $order_info->OrderStrategy()->order_detail($order_info);
        if ($provider_order_detail->isTicketed() && $order_info->isTicketing()) {
            Log::info("计划任务拉取出票中的订单状态:{$order_info->getOrderSn()}");
            event(new PlaneOrderTicketedEvent($order_info, $provider_order_detail->getTicketedPassengers()));
        }
    }


    private function ticket_failed(PlaneOrder $order_info)
    {
        // TODO 目前从订单详情 拉不到失败是啥样的
    }
}
